﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using dwindleUrl.Models;
using dwindleUrl.Repositories;
using Microsoft.Practices.Prism.Commands;
using Microsoft.Practices.Prism.Mvvm;
using Microsoft.Practices.Prism.Mvvm.Interfaces;

namespace dwindleUrl.ViewModels
{
    public class DetailsPageViewModel : ViewModel,IDetailsPageViewModel
    {
        private INavigationService _navigationServic;
        private IItemRepository _itemRepository;

        public DetailsPageViewModel(INavigationService navigationservice, IItemRepository itemRepository)
        {
            _navigationServic = navigationservice;
            _itemRepository = itemRepository;
        }

        Models.Item _item = default(Models.Item);
        [RestorableState]
        public Models.Item Item { get { return _item; } set { SetProperty(ref _item, value); } }

        private DelegateCommand _GoBackCommand = null;
        public DelegateCommand GoBackCommand
        {
            get
            {
                if (_GoBackCommand != null)
                    return _GoBackCommand;
                _GoBackCommand = new DelegateCommand
                (
                    () => { _navigationServic.GoBack();},
                    () => true);
                this.PropertyChanged += (s, e) => _GoBackCommand.RaiseCanExecuteChanged();
                return _GoBackCommand;
            }
        }

        public override void OnNavigatedTo(object navigationParameter, NavigationMode navigationMode, Dictionary<string, object> viewModelState)
        {
            base.OnNavigatedTo(navigationParameter, navigationMode, viewModelState);
            if (!viewModelState.Any())
            {
                this.Item = _itemRepository.AllItems()
                    .First(x => x.Text == navigationParameter.ToString());
            }
        }
    }
}
